//
//  NewsDetailViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2017/1/3.
//  Copyright © 2017年 van7ish. All rights reserved.
//

#import "NewsDetailViewController.h"

@interface NewsDetailViewController () <UIWebViewDelegate, UIScrollViewDelegate>

/** 导航条 */
@property (nonatomic, strong) UIImageView * navBar;
/** 标题 */
@property (nonatomic, strong) UILabel * titleLabel;
/** 时间 */
@property (nonatomic, strong) UIView * timeView;
/** 新闻内容 */
@property (nonatomic, strong) UIWebView * webView;
/** html已加载 */
@property (nonatomic, assign) BOOL loaded;

@property (nonatomic, copy) NSString *htmlStr;

@end

@implementation NewsDetailViewController

- (UIWebView *)webView{
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_W, SCREEN_H - 64)];
        _webView.delegate = self;
        _webView.scrollView.bounces = NO;
        
        
        self.htmlStr =self.dataDic[@"content"] ? : self.dataDic[@"summary"];
        
        if (![self.htmlStr containsString:@"src=\"http://"]) {
            //html文本中图片路径补全
            NSString *htmls = [NSString stringWithFormat:@"<html> \n"
                               "<head> \n"
                               "<style type=\"text/css\"> \n"
                               "body {font-size:15px;}\n"
                               "</style> \n"
                               "</head> \n"
                               "<body>"
                               "<script type='text/javascript'>"
                               "window.onload = function(){\n"
                               "var $img = document.getElementsByTagName('img');\n"
                               "for(var p in  $img){\n"
                               "var httpP = \"%@\" +$img[p].getAttribute(\"src\");"
                               "$img[p].setAttribute(\"src\",httpP);"    // 这里发现拼接图片地址也能成功了。
                               "$img[p].style.width = '60%%';\n"
                               "$img[p].style.height ='auto'\n"
                               "}\n"
                               "}"
                               "</script>%@"
                               "</body>"
                               "</html>", @"http://jctsg.ndlib.cn", self.dataDic[@"content"] ? : self.dataDic[@"summary"]]; // 这里的webInfo就是原始的HTML字符串。
            [_webView loadHTMLString:htmls baseURL:nil];
        } else {
            
            //html文本中图片路径补全
            NSString *htmls = [NSString stringWithFormat:@"<html> \n"
                               "<head> \n"
                               "<style type=\"text/css\"> \n"
                               "body {font-size:15px;}\n"
                               "</style> \n"
                               "</head> \n"
                               "<body>"
                               "<script type='text/javascript'>"
                               "window.onload = function(){\n"
                               "var $img = document.getElementsByTagName('img');\n"
                               "for(var p in  $img){\n"
                               "$img[p].style.width = '60%%';\n"
                               "$img[p].style.height ='auto'\n"
                               "}\n"
                               "}"
                               "</script>%@"
                               "</body>"
                               "</html>", self.dataDic[@"content"] ? : self.dataDic[@"summary"]];
            [_webView loadHTMLString:htmls baseURL:nil];
            
            _webView.scalesPageToFit = YES;
            
        }
        

        
    }
    return _webView;
}

- (UIImageView *)navBar{
    if (!_navBar) {
        _navBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 64)];
        _navBar.image = ImageNamed(@"daohangtiao");
    }
    return _navBar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;
    
    [self.view addSubview:self.navBar];
    
    [self.view addSubview:self.webView];
    
    //添加统计
    [self requestStatistics];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - UIWebViewDelegate Method

-(void)webViewDidFinishLoad:(UIWebView *)webView
{

    //图片尺寸适配
    NSString *maxWidth = [NSString stringWithFormat:@"%f", WidthScale(414)];
        
    [webView stringByEvaluatingJavaScriptFromString:
     [NSString stringWithFormat:@"var script = document.createElement('script');"
      "script.type = 'text/javascript';"
      "script.text = \"function ResizeImages() { "
      "var myimg,oldwidth;"
      "var maxwidth=%@;" //缩放系数
      "for(i=0;i <document.images.length;i++){"
      "myimg = document.images[i];"
      "if(myimg.width > maxwidth){"
      "oldwidth = myimg.width;"
      "myimg.width = maxwidth;"
      "myimg.height = maxwidth*myimg.height/myimg.width;"
      "}"
      "}"
      "}\";"
      "document.getElementsByTagName('head')[0].appendChild(script);", maxWidth]
     ];
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    
    

    
    
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    ;
    
    //禁止webView中的超链接跳转
    if (self.loaded == NO) {
        self.loaded = YES;
        return YES;
    } else {
        return NO;
    }
}

/** 添加统计 */
- (void)requestStatistics{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        //1、图书；2、视频；3、音频；4、期刊杂志5、县域视频6、资讯
        NSString *URL = [NSString stringWithFormat:Kstatistics, KHostAddress, KCurrentIP, [AppDelegate shareDelegate].userModel.userId, KOrganizationID, @(6), self.dataDic[@"id"]];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加统计成功");
            } else {
                DLog(@"添加统计失败");
            }
        } failure:^(NSError *error) {
            DLog(@"%@", error);
        }];
    }
}
@end
